package top.zlhy7.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.zlhy7.model.UserVo;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author 任勇
 * @date 2020/12/10 23:08
 * @description 查询数据库，框架指定调用
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    /**
     * spring上下文
     */
    @Autowired
    private ApplicationContext applicationContext;
    /**
     * 密码加密器
     */
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 模拟人员数据
     */
    public static List<UserVo> userVoList;
    /**
     * 查询数据库获取真实用户信息
     * @param loginUser
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String loginUser) throws UsernameNotFoundException {
        if(!"user".equals(loginUser)){
            return null;
        }
        //操作权限
        List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.createAuthorityList("admin","user");
        return new User("user", passwordEncoder.encode("123456"), grantedAuthorityList);
    }

    /**
     * 手动初始化一些用户
     */
    @PostConstruct
    public void init(){
        System.out.println(this.userVoList);
        Binder binder = Binder.get(applicationContext.getEnvironment());
        // 绑定List配置
        List<UserVo> post = binder.bind("consumer.userList", Bindable.listOf(UserVo.class)).get();
        System.out.println(post);
    }
}
